package com.work.demo.filter;

import com.work.demo.entity.UserDto;
import com.work.demo.utils.UserThradLocal;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("--------------------- LoginInterceptor 开始 -------------------");
        long startTime = System.currentTimeMillis();
        request.setAttribute("requestStartTime", startTime);
        UserDto userDto = new UserDto();
        userDto.setName("王五");
        userDto.setPassword("123456");
        UserThradLocal.set(userDto);


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        Long startTime = (Long) request.getAttribute("requestStartTime");
        log.info("---------------------- LoginInterceptor 结束 耗时:{} ms ------------------", System.currentTimeMillis() - startTime);

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        UserThradLocal.clear();
        log.info("LoginInterceptor 结束");
    }

}
